#include "Gets.h"

bool GetIntersectVec3( ID3DXMesh* pMesh, D3DXVECTOR3& intersectVec3 )
{
	POINT pt;
	GetCursorPos( &pt );

	ScreenToClient( GetHwnd(), &pt );

	float w = GetBackBufferWidth();
	float h = GetBackBufferHeight();

	float ux =  2 * pt.x / w - 1;
	float uy = -2 * pt.y / h + 1;

	float x = ux / ( GetProj() )( 0, 0 );
	float y = uy / ( GetProj() )( 1, 1 );

	D3DXVECTOR3 vec3Origin = D3DXVECTOR3( 0.0f, 0.0f, 0.0f );
	D3DXVECTOR3 vec3Dir	= D3DXVECTOR3( x, y, 1.0f );

	D3DXMATRIX invView;
	D3DXMatrixInverse( &invView, NULL, &GetView() );

	D3DXVec3TransformCoord( &vec3Origin, &vec3Origin, &invView );
	D3DXVec3TransformNormal( &vec3Dir, &vec3Dir, &invView );
	D3DXVec3Normalize( &vec3Dir, &vec3Dir );

	intersectVec3 = D3DXVECTOR3( 0.0f, 0.0f, 0.0f );
	BOOL bHit = false;
	DWORD pFaceIndex;
	float u, v, dist;
	D3DXIntersect( pMesh, &vec3Origin, &vec3Dir, &bHit, &pFaceIndex, &u, &v, &dist, NULL, NULL );

	if( bHit )
	{
		intersectVec3 = vec3Origin + dist * vec3Dir;
		return true;
	}
	else return false;
}